package com.example.demo.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import com.example.demo.framework.base.BaseRepository;
import com.example.demo.model.Item;

public interface ItemRepository
		extends JpaRepository<Item, Long>, JpaSpecificationExecutor<Item>, BaseRepository<Item, Long> {

	@SuppressWarnings("serial")
	public default Page<Item> pageCriteria(Item item, Pageable pageable) {

		Page<Item> page = this.findAll(new Specification<Item>() {
			@Override
			public Predicate toPredicate(Root<Item> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				if (item.getStatus() != null) {
					list.add(cb.equal(root.<Integer> get("status"), item.getStatus()));
				}
				if (StringUtils.isNotEmpty(item.getItemID())) {
					list.add(cb.equal(root.<String> get("itemID"), item.getItemID()));
				}
				if (StringUtils.isNotEmpty(item.getTitle())) {
					list.add(cb.like(root.<String> get("title"), "%" + item.getTitle() + "%"));
				}
				cb.desc(root.<Long> get("iID"));

				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}

		}, pageable);
		return page;
	}

	@Query("select new Map(c.name as name,i.title as title,i.itemCode as itemCode,i.price as price,i.itemURL as itemURL,"
			+ "i.imageURL as imageURL,i.brand as brand,i.skuStr as skuStr,i.modifyTime as modifyTime,i.marketTime as marketTime,i.status as status) "
			+ "from Item i left join Category c on i.categoryID=c.categoryID where i.status=1")
	public Page<Map<String, Object>> pageItem(Pageable pageable);

	@Query("select new Map(c.name as name,i.title as title,i.itemCode as itemCode,i.price as price,i.itemURL as itemURL,"
			+ "i.imageURL as imageURL,i.brand as brand,i.skuStr as skuStr,i.modifyTime as modifyTime,i.marketTime as marketTime,i.status as status) "
			+ "from Item i left join Category c on i.categoryID=c.categoryID where i.status=1 and i.itemID like CONCAT('%',?1,'%')")
	public Page<Map<String, Object>> pageItemByItemID(String itemID, Pageable pageable);

	@Query("from Item i where i.itemID = ?1 and i.status=1")
	public Item getByItemID(String itemID);
	
	@Query("from Item i where i.iID = ?1")
	public Item getByID(long iID);
}
